(library (docker-socket)
  (export connect-to-docker-socket
          call-with-output-docker-socket)
  (import (rnrs base)
          (only (guile)
                lambda* λ
                ;; sockets stuff
                AF_UNIX
                PF_UNIX
                SOCK_STREAM
                SOL_SOCKET
                SO_REUSEADDR
                make-socket-address
                socket
                setsockopt
                connect
                close)
          (web client)
          (web uri)
          (ice-9 iconv)))


(define connect-to-docker-socket
  (lambda* (#:key (socket-path "/var/run/docker.sock"))
    (let ([docker-sock-addr (make-socket-address AF_UNIX socket-path)]
          [docker-sock (socket PF_UNIX SOCK_STREAM 0)])
      ;; socket options:
      ;; https://www.gnu.org/software/libc/manual/html_node/Socket_002dLevel-Options.html
      (setsockopt docker-sock SOL_SOCKET SO_REUSEADDR 1)
      ;; usage of connect:
      ;; https://www.gnu.org/software/guile/manual/html_node/Network-Sockets-and-Communication.html#Network-Sockets-and-Communication
      ;; server side would use `bind`, `accept` and `listen`.
      ;; client side uses `connect` and `close`.
      (connect docker-sock docker-sock-addr)
      docker-sock)))


(define call-with-output-docker-socket
  (lambda* (proc #:key (socket-location "/var/run/docker.sock"))
    (let ([socket (connect-to-docker-socket #:socket-path socket-location)])
      (proc socket)
      (close socket))))
